<?php

namespace app\xs_ai\controller\api;

use think\facade\Db;
use xsframe\base\ApiBaseController;
use xsframe\exception\ApiException;
use xsframe\facade\service\DbServiceFacade;
use xsframe\util\RequestUtil;

class Ai extends ApiBaseController
{
    private $config = [
        'shunWang' => [
            'Authorization' => '4ce3962699a2004eb5d7b47bd7af1834'
        ]
    ];

    // 翻译接口 http://www.xsframe.com/xs_ai/api/ai/translation
    public function translation(): \think\response\Json
    {
        $content = trim($this->params['content']);
        if (empty($content)) {
            $content = "你好";
        }

        $result = $this->doTranslation($content);
        return $this->success($result);
    }

    // 中文翻译成英文
    private function doTranslation($content = "")
    {
        $url = "https://ai.zishuju.cn/ai/api/text/Translation";
        $dataString = '{"model": "qwen-mt-turbo", "messages": [{"role": "user", "content": "' . $content . '"} ], "translation_options": {"source_lang": "Chinese", "target_lang": "English"} }';
        $ret = RequestUtil::httpPostJson($url, json_decode($dataString, true), true);
        return json_decode($ret, true);
    }

    // 生成图片 http://www.xsframe.com/xs_ai/api/ai/doImage
    public function doImage(): \think\response\Json
    {
        $url = "https://api.shunwangai.com:24580/aigc/generate";

        // mode: 1, // 0:推荐 1:自定义 4:商品图
        // content: '', // 内容
        // activeSceneType: '智能推荐', // 画面类型
        // pictureType: 'vertical', // 图片类型 vertical square horizontal
        // pictureCount: 2, // 生成数量
        // notContent: '', // 不存在内容
        // imageFilename: '', // 图片存储地址
        // imageUrl: '', // 图片url地址
        // imageProportion: 1, // 图片权重比例 1~10
        // templateType: 1, // 模板类型 1商品模板 2文字描述
        // selTemplateItem: {}, // 1商品模板详细内容,

        $mode = intval($this->params['mode'] ?? '');
        $content = trim($this->params['content'] ?? '');
        $notContent = trim($this->params['notContent'] ?? '');
        $activeSceneType = trim($this->params['activeSceneType'] ?? '');
        $pictureType = trim($this->params['pictureType'] ?? 'vertical');
        $pictureCount = intval($this->params['pictureCount'] ?? 1);
        $imageFilename = trim($this->params['imageFilename'] ?? '');
        $imageUrl = trim($this->params['imageUrl'] ?? '');
        $imageProportion = intval($this->params['imageProportion'] ?? 1);
        $templateType = intval($this->params['templateType'] ?? 1);
        $selTemplateItem = $this->params['selTemplateItem'] ?? [];

        if (!empty($activeSceneType)) {
            $content .= ' 画面类型:' . $activeSceneType;
        }
        if (!empty($notContent)) {
            $content .= ' 不要出现:' . $notContent;
        }

        $translationRet = $this->doTranslation($content);
        $content = $translationRet['choices'][0]['message']['content'];

        $height = 0;
        $width = 0;
        if ($pictureType == 'vertical') {
            $height = 1600;
            $width = 900;
        } else {
            if ($pictureType == 'square') {
                $height = 1600;
                $width = 1600;
            } else {
                if ($pictureType == 'horizontal') {
                    $height = 900;
                    $width = 1600;
                }
            }
        }

        $dataArray = [
            'service_name' => 'aigc',
            'request_body' => [
                'prompt'            => $content,
                'height'            => $height,
                'width'             => $width,
                'relative_strength' => 'highest'
            ],
        ];

        if (!empty($imageUrl)) {
            $dataArray['relative_image'] = base64_encode(file_get_contents($imageUrl));
        }

        $dataString = json_encode($dataArray);

        // $dataString = '{"service_name": "aigc", "request_body": {"prompt": "A Chinese beauty wearing Hanfu, her hair fluttering in the wind. Then the camera switches to a frontal close-up. Background Zhangjiajie", "height": 1024}}';
        // dump($dataString);

        $header = [
            'Authorization' => 'Bearer ' . $this->config['shunWang']['Authorization']
        ];

        $prompt_ids = [];
        $prompt_ids_data = [];

        for ($i = 1; $i <= $pictureCount; $i++) {
            $ret = RequestUtil::httpPostJson($url, json_decode($dataString, true), $header);
            $ret = json_decode($ret, true);

            if ($ret['code'] == 200) {
                $prompt_ids[] = $ret['data']['prompt_id'];
                $prompt_ids_data[$ret['data']['prompt_id']] = [
                    'prompt_id' => $ret['data']['prompt_id'],
                    'status'    => 0
                ];
            }
        }

        $data = [
            'mode'            => $mode,
            'content'         => $content,
            'notContent'      => $notContent,
            'activeSceneType' => $activeSceneType,
            'pictureType'     => $pictureType,
            'pictureCount'    => $pictureCount,
            'imageFilename'   => $imageFilename,
            'imageUrl'        => $imageUrl,
            'imageProportion' => $imageProportion,
            'templateType'    => $templateType,
            'selTemplateItem' => $selTemplateItem,
            'prompt_ids'      => $prompt_ids
        ];

        $logId = DbServiceFacade::name("xs_ai_log")->insertInfo([
            'uniacid'    => $this->uniacid,
            'token'      => trim($this->header['token'] ?? ''),
            'data'       => serialize($data),
            'prompt_ids' => serialize($prompt_ids_data),
            'createtime' => TIMESTAMP,
        ]);

        $result = [
            'log_id'     => $logId,
            'prompt_ids' => $prompt_ids
        ];
        return $this->success($result);
    }

    // 读取图片 http://www.xsframe.com/xs_ai/api/ai/getImage?prompt_id=c42650c8-b3fd-4d17-9b90-3ee760f61203
    public function getImage(): \think\response\Json
    {
        $logId = trim($this->params['log_id'] ?? '');
        $promptId = trim($this->params['prompt_id'] ?? '');

        $url = "https://api.shunwangai.com:24580/aigc/preview";

        // $dataString = '{"prompt_id": "4c772198-4e4a-44e6-9051-5f1b4d421f73"}';
        $dataString = '{"prompt_id": "' . $promptId . '"}';

        $header = [
            'Authorization' => 'Bearer ' . $this->config['shunWang']['Authorization']
        ];
        $ret = RequestUtil::httpPostJson($url, json_decode($dataString, true), $header);
        $ret = json_decode($ret, true);

        $logInfo = DbServiceFacade::name("xs_ai_log")->getInfo([
            'uniacid' => $this->uniacid,
            'id'      => $logId
        ]);

        $thumbs_urls = [];
        if (empty($logInfo['thumbs_urls'])) {
            $thumbs_urls = unserialize($logInfo['thumbs_urls']);
        }

        $promptIdsData = [];
        if (empty($logInfo['prompt_ids'])) {
            $promptIdsData = unserialize($logInfo['prompt_ids']);
        }

        $error_prompt_ids = [];
        if (empty($logInfo['error_prompt_ids'])) {
            $error_prompt_ids = unserialize($logInfo['error_prompt_ids']);
        }

        if ($ret['code'] != 200 || in_array($ret['data']['status'], [3, 4, 5])) {
            $error_prompt_ids[] = $promptId;

            DbServiceFacade::name("xs_ai_log")->updateInfo([
                'error_prompt_ids' => serialize($error_prompt_ids),
                'updatetime'       => TIMESTAMP,
            ], [
                'id' => $logId
            ]);
        } else {
            if ($ret['data']['status'] == 2) {
                if ($promptIdsData[$promptId]['status'] == 0) {
                    $ret['data']['images'][0]['base64_data'] = "data:image/png;base64," . $ret['data']['images'][0]['base64_data'];
                    $thumbs_urls[] = "data:image/png;base64," . $ret['data']['images'][0]['base64_data'];

                    $promptIdsData[$promptId]['status'] = 1;
                    DbServiceFacade::name("xs_ai_log")->updateInfo([
                        'prompt_ids'  => serialize($promptIdsData),
                        'thumbs_urls' => serialize($thumbs_urls),
                        'updatetime'  => TIMESTAMP,
                    ], [
                        'id' => $logId
                    ]);
                }
            }
        }

        // echo "<img src='data:image/png;base64,{$ret['data']['images'][0]['base64_data']}'>";
        return $this->success($ret['data']);
    }
}
